const moment = require("moment");
const router = require("koa-router")();

/**
 *
 * api {get} /home/app/plugins/smsFee 获取短信验证码费用
 *
 */
router.get("/smscode/smsFee", async (ctx, nex) => {
  const baas = ctx.baas;
  const smsFee = await BaaS.Models.sms_fee.query({}).fetchAll();
  ctx.success(smsFee);
});
/**
 *
 * api {get} /home/app/plugins/smscode/page 获取短信验证码列表
 *
 */
router.get("/smscode/page/:page", async (ctx, nex) => {
  const page = ctx.params.page;
  const baas = ctx.baas;
  const smsList = await BaaS.Models.plugins_smscode
    .query({ where: { baas_id: baas.id } })
    .fetchPage({
      pageSize: ctx.config.pageSize,
      page: page,
      withRelated: []
    });
  // 获取短信信息
  const sms = await BaaS.Models.sms
    .query({ where: { baas_id: baas.id } })
    .fetch();
  Object.assign(smsList, { number: sms.number });
  ctx.success(smsList);
});
/**
 *
 * api {get} /home/app/plugins/smscode/log 获取发送短信日志
 *
 */
router.get("/smscode/log", async (ctx, nex) => {
  const baas = ctx.baas;
  const { page } = ctx.query;

  const smsLog = await BaaS.Models.sms_log
    .query({ where: { baas_id: baas.id } })
    .fetchPage({
      pageSize: ctx.config("pageSize"),
      page: page,
      withRelated: []
    });
  ctx.success(smsLog);
});
/**
 *
 * api {get} /home/app/plugins/smscode/id/:id 获取短信验证码列表
 *
 */
router.get("/smscode/id/:id", async (ctx, nex) => {
  const id = ctx.params.id;
  const baas = ctx.baas;
  const smsCode = await BaaS.Models.plugins_smscode
    .query({ where: { id: id, baas_id: baas.id } })
    .fetch();
  ctx.success(smsCode);
});
/**
 *
 * api {post} /home/app/plugins/buy 短信验证码费用充值
 *
 * apiParam {Number} id 短信费用id
 *
 */
router.post("/smscode/Recharge", async (ctx, nex) => {
  const user = ctx.user;
  const baas = ctx.baas;
  const { id } = ctx.post;
  // 查询费用设置
  const smsFee = await BaaS.Models.sms_fee.query({ where: { id: id } }).fetch();
  if (!smsFee) {
    ctx.error("暂无费用选项");
    return;
  }
  // 扣除账户余额，用户额度是100
  user.money -= smsFee.price;
  if (parseInt(user.money) < ctx.config("credits")) {
    ctx.error("账户余额不足");
    return;
  }
  BaaS.Models.user.forge({ id: user.id, money: user.money }).save();
  // 新增短信条数
  const sms = await BaaS.Models.sms
    .query({ where: { baas_id: baas.id } })
    .fetch();

  if (!sms) {
    await BaaS.Models.sms
      .forge({ baas_id: baas.id, number: smsFee.number })
      .save();
  } else {
    await BaaS.Models.sms
      .forge({ id: sms.id, number: sms.number + smsFee.number })
      .save();
  }
  // 添加log日志
  BaaS.Models.cost_log
    .forge({
      user_id: user.id,
      money: smsFee.price,
      orderid: moment().format("YYMMDDHHmmssS"),
      type: 1,
      status: 1,
      remark: "短信费用充值"
    })
    .save();
  ctx.success("充值成功");
});
/**
 *
 * api {post} /home/app/plugins/smscode/add 获取短信验证码列表
 *
 * apiParam {String} name 短信验证名称
 * apiParam {String} content 短信验证内容
 */
router.post("/smscode/add", async (ctx, nex) => {
  const baas = ctx.baas;
  const { id, name, content } = ctx.post;
  if (!name || !content) {
    ctx.error("完善表单");
    return;
  }
  const key = `name:${name}:content:${content}`;
  const locked = await BaaS.redis.lock(key);
  if (locked) {
    const result = await BaaS.Models.plugins_smscode
      .forge({
        id: id,
        baas_id: baas.id,
        name: name,
        content: content
      })
      .save();
    ctx.success(result);

    await BaaS.redis.unlock(key);
  } else {
    ctx.error("系统繁忙，请稍后重试");
    console.log(`${key} Waiting`);
    return;
  }
});
/**
 *
 * api {get} /home/app/plugins/smscode/del/:id 删除短信验证码
 *
 */
router.get("/smscode/del/:id", async (ctx, nex) => {
  const id = ctx.params.id;
  const baas = ctx.baas;
  const smsCode = await BaaS.Models.plugins_smscode
    .forge({ id: id, baas_id: baas.id })
    .destroy();
  ctx.success(smsCode);
});

module.exports = router;
